<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编号" prop="cdNumber">
              <el-input v-model="queryParams.cdNumber" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="城代名称" prop="cdName">
              <el-input v-model="queryParams.cdName" placeholder="请输入城代名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="cdPhonenumber">
              <el-input v-model="queryParams.cdPhonenumber" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:agentCd:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:agentCd:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="agentCdList" @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="scope">
            <el-card shadow="never" style="width: 75%">
              <template #header>营收信息</template>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-statistic :value="scope.row.amountIncomeBusiness" :value-style="{ 'color': '#409eff' }">
                    <template #title>
                      <div style="display: inline-flex; align-items: center; color: #409eff">总营收</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="8">
                  <el-statistic :value="scope.row.amountIncomeToday" :value-style="{ 'color': '#e6a23c' }">
                    <template #title>
                      <div style="display: inline-flex; align-items: center; color: #e6a23c">今日营收</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="8">
                  <el-statistic :value="scope.row.amountIncomeMonth" :value-style="{ 'color': '#e6a23c' }">
                    <template #title>
                      <div style="display: inline-flex; align-items: center; color: #e6a23c">本月营收</div>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </el-card>
            <el-card shadow="never" style="margin-top: 10px; width: 75%">
              <template #header>推广信息</template>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-statistic :value="scope.row.mrTotal">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">医代数量</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic :value="scope.row.mrTotalToday">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">今日新增医代</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic :value="scope.row.storeTotal">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">诊所数量</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic :value="scope.row.storeTotalToday">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">今日新增诊所</div>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </el-card>
            <el-card shadow="never" style="margin-top: 10px; width: 75%">
              <template #header>消耗信息</template>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-statistic :value="scope.row.storeTotal">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">诊所数量</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic :value="scope.row.balanceCurrent">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">可用次数</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic :value="scope.row.balanceUsed">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">消耗次数</div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic :value="scope.row.balanceUsedToday">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">今日消耗</div>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </el-card>
          </template>
        </el-table-column>
        <el-table-column label="所属国代" align="center" prop="agentGdName" />
        <el-table-column label="所属省代" align="center" prop="agentSdName" />
        <el-table-column label="编号" align="center" prop="cdNumber" />
        <el-table-column label="城代名称" align="center" prop="cdName" />
        <el-table-column label="联系电话" align="center" prop="cdPhonenumber" />
        <el-table-column label="省/市/区" align="center" prop="province">
          <template #default="scope"> {{ scope.row.province }}/{{ scope.row.city }}/{{ scope.row.district }} </template>
        </el-table-column>
        <el-table-column label="详细地址" align="center" prop="address" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="busi_agent_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="scope.row.status === 0" content="修改" placement="top">
              <el-button v-hasPermi="['business:agentCd:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.userId !== 1 && scope.row.status === 0" content="重置密码" placement="top">
              <el-button v-hasPermi="['business:agentCd:edit']" link type="primary" icon="Key" @click="handleResetPwd(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === 0" content="删除" placement="top">
              <el-button v-hasPermi="['business:agentCd:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改城代管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="680px" append-to-body>
      <el-form ref="agentCdFormRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item v-if="form.id" label="编号" prop="cdNumber">
          <el-input v-model="form.cdNumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item v-if="form.id" label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" maxlength="30" disabled />
        </el-form-item>
        <el-form-item label="城代名称" prop="cdName">
          <el-input v-model="form.cdName" placeholder="请输入城代名称" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" maxlength="30" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="登录密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入登录密码" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="联系电话" prop="cdPhonenumber">
          <el-input v-model="form.cdPhonenumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="省/市/区" prop="province">
          <el-cascader v-model="form.regionInfo" :options="regionInfoOptions" :props="props" @change="handleChange" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="开关-接收消息" prop="switchMsg">
          <el-radio-group v-model="form.switchMsg">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AgentCd" lang="ts">
import { listAgentCd, getAgentCd, delAgentCd, addAgentCd, updateAgentCd, resetUserPwd } from '@/api/business/agentCd';
import { AgentCdVO, AgentCdQuery, AgentCdForm } from '@/api/business/agentCd/types';
import CnRegionInfo from '@/assets/data/cn_region_info.json';
import { to } from 'await-to-js';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { busi_agent_status, sys_normal_disable } = toRefs<any>(proxy?.useDict('busi_agent_status', 'sys_normal_disable'));

const agentCdList = ref<AgentCdVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const agentCdFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const props = {
  expandTrigger: 'hover' as const
};
const regionInfoOptions = CnRegionInfo;

const initFormData: AgentCdForm = {
  id: undefined,
  agentGdId: undefined,
  agentSdId: undefined,
  sysUserId: undefined,
  cdNumber: undefined,
  cdName: undefined,
  cdPhonenumber: undefined,
  country: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  address: undefined,
  switchMsg: 0,
  status: 0,
  otherVal: undefined,
  remark: undefined
};
const data = reactive<PageData<AgentCdForm, AgentCdQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    agentGdId: undefined,
    agentSdId: undefined,
    sysUserId: undefined,
    cdNumber: undefined,
    cdName: undefined,
    cdPhonenumber: undefined,
    country: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    address: undefined,
    switchMsg: undefined,
    status: undefined,
    otherVal: undefined,
    createTime: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    cdName: [{ required: true, message: '城代名称不能为空', trigger: 'blur' }],
    username: [
      { required: true, message: '登录账号不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '登录账号长度必须介于 2 和 20 之间', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '登录密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '登录密码长度必须介于 5 和 20 之间', trigger: 'blur' }
    ],
    cdPhonenumber: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    province: [{ required: true, message: '省/市/区不能为空', trigger: 'blur' }],
    city: [{ required: true, message: '省/市/区不能为空', trigger: 'blur' }],
    switchMsg: [{ required: true, message: '开关-接收消息不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询城代管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAgentCd(queryParams.value);
  agentCdList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  agentCdFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AgentCdVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加城代';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AgentCdVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getAgentCd(_id);
  Object.assign(form.value, res.data);
  let regionInfo = [];
  if (form.value.province !== undefined) {
    regionInfo.push(form.value.province);
  }
  if (form.value.city !== undefined) {
    regionInfo.push(form.value.city);
  }
  if (form.value.district !== undefined) {
    regionInfo.push(form.value.district);
  }
  form.value.regionInfo = regionInfo;
  dialog.visible = true;
  dialog.title = '修改城代';
};

/** 提交按钮 */
const submitForm = () => {
  agentCdFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAgentCd(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAgentCd(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AgentCdVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除城代编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delAgentCd(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/agentCd/export',
    {
      ...queryParams.value
    },
    `agentCd_${new Date().getTime()}.xlsx`
  );
};

const handleChange = (value: string) => {
  form.value.province = value[0];
  form.value.city = value[1];
  if (value.length === 3) {
    form.value.district = value[2];
  } else {
    form.value.district = '';
  }
};

/** 重置密码按钮操作 */
const handleResetPwd = async (row: AgentCdVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入城代"' + row.cdName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
    })
  );
  if (!err) {
    await resetUserPwd(row.sysUserId, res.value);
    proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value);
  }
};

onMounted(() => {
  getList();
});
</script>
